﻿var me = this,
    draftId = PAI.Global.getUrlData('draftId'),
    vm = this.lookupViewModel(),
    showTipsMsg = function (msg) {
        Ext.toast({
            html: msg,
            closable: false,
            align: 't',
            slideDUration: 400,
            maxWidth: 400
        });
    },
    checkIsNull = function (currentData, fields, msgTpl) {
        for (var key in currentData) {
            if (Ext.Array.contains(fields, key)) {
                if ((key == 'Quantity' || key == 'UnitPrice') && currentData[key] == 0) {
                    showTipsMsg(Ext.String.format(msgTpl, key));
                    return false;
                } else if ((currentData[key] == "" && currentData[key] !== 0) || currentData[key] == undefined || currentData[key] == null) {
                    showTipsMsg(Ext.String.format(msgTpl, key));
                    return false;
                }
            }
        }
        return true;
    }

//复制表单ID
var formDataId = PAI.Global.getUrlData('formDataId');
//ExpenseType值
var expenseType = ref.ExpenseType.getValue();

var grid1 = ref.datagrid1;
var grid2 = ref.datagrid2;
var grid3 = ref.datagrid3;
var grid4 = ref.datagrid4;
var grid5 = ref.datagrid5;
var grid6 = ref.datagrid6;

var store1 = grid1.getStore(),
    store2 = grid2.getStore(),
    store3 = grid3.getStore(),
    store4 = grid4.getStore(),
    store5 = grid5.getStore(),
    store6 = grid6.getStore();

var vendorGrid = ref.datagrid1;
var vendorStore = vendorGrid.getStore();

if (me.analysis.status == 'launch' || draftId || formDataId || me.analysis.status == 'resubmit' || me.analysis.status == '重新提交') {
    if (vendorStore.data.items.length == 0) {
        showTipsMsg('Please fill in the VendorInformation');
        return false;
    }

    if (vendorStore.data.items.length > 0) {
        for (var i = 0; i < vendorStore.data.items.length; i++) {
            var name = vendorStore.data.items[i].data.Name;
            if (name == "" || name == undefined || name == null) {
                showTipsMsg('Please fill Name in the VendorInformation')
                return false;
            }
        }
    }


    if (store2.data.items.length == 0) {
        showTipsMsg('Please fill in Purchase Items section');
        return false;
    }
    //Attachments附件必填
    if (ref.file8.store.getCount() == 0) {
        showTipsMsg('Please upload necessary files in the General Information part');
        return false;
    }

    if (ref.UKCrossCharge.getValue() == 'yes') {
        //UK GL Code不能为空
        if (ref.UKGLCode.getValue().match(/^[ ]*$/)) {
            showTipsMsg('Please key in UK GL Code in the Finance Information part');
            return false;
        }

        //UK Cost Center不能为空
        if (ref.UKCostCenter.getValue().match(/^[ ]*$/)) {
            showTipsMsg('Please key in UK Cost Center in the Finance Information part');
            return false;
        }

        var uKCrossCharge = ref.UKCrossCharge.getValue();
        var projectX = ref.ProjectX.getValue();
        if (uKCrossCharge == "yes") {
            //附件必填  
            if (ref.file7.store.getCount() == 0) {
                showTipsMsg('Please upload necessary files in the Finance Information part');
                return false;
            }
        }
    }

    //判断列表是否为空
    if (store2.data.items.length > 0) {
        var fields = ['DescriptionOfSuppliesServices', 'ProjectActivity', 'DeliveryDateStart', 'DeliveryDateEnd', 'MaterialGroup', 'Quantity', 'UnitPrice'];

        for (var i = 0; i < store2.data.items.length; i++) {
            var currentData = store2.data.items[i].data,
                msgTpl = 'Please fill in {0} in the Purchase Items section.';

            var returnValue = checkIsNull(currentData, fields, msgTpl);

            if (!returnValue) {
                return returnValue;
            }
        }
    } else {
        showTipsMsg('Please fill in Purchase Items Information');
        return false;
    }

    if (ref.UKCrossCharge.getValue() == 'no') {

        //Company Allocation 提交非空验证
        if (store3.data.items.length > 0) {
            var fields = ['DescriptionOfSuppliesServices', 'ProjectActivity', 'Company', 'CompanySharingRatio', 'Cost'];

            for (var i = 0; i < store3.data.items.length; i++) {

                var currentData = store3.data.items[i].data,
                    msgTpl = 'Please fill in {0} in the CompanyAllocation section.';

                var returnValue = checkIsNull(currentData, fields, msgTpl);

                if (!returnValue) {
                    return returnValue;
                }
            }

            //需要对Company Allocation中相同的 Desceiption,ProjectActivity的 CompanySharingRatio 作100%判断.
            var sameObj = {};

            Ext.each(store3.data.items, function (record) {
                var key = record.get('DescriptionOfSuppliesServices') + '_' + record.get('ProjectActivity');
                //相同的 Description + ProjectActivity,就把CompanySharingRatio相加
                /* 结构如下,相同的Description + ProjectActivity 必须等于100.
                    {
                        value_value1: 100,
                        value_value2: 90,
                    }
                 */
                if (!sameObj[key]) {
                    sameObj[key] = record.get('CompanySharingRatio');
                } else {
                    sameObj[key] += record.get('CompanySharingRatio');
                }
            });
            for (var k in sameObj) {
                if (sameObj[k] != 100) {
                    showTipsMsg('In Company Allocation, the CompanySharingRatio for the same Desceiption and ProjectActivity must equal 100%.Please be sure!');
                    return false;
                }
            }
        } else {
            showTipsMsg('Please fill in Company Allocation Information part');
            return false;
        }
    }

    //Brand Allocation(JLRC) 提交非空验证
    if (store4.data.items.length > 0) {
        var fields = ['DescriptionOfSuppliesServices', 'ProjectActivity', 'JASharingRatio', 'JACost', 'JACostCenter', 'LRSharingRatio', 'LRCost', 'LRCostCenter'];

        for (var i = 0; i < store4.data.items.length; i++) {
            var currentData = store4.data.items[i].data,
                msgTpl = 'Please fill in {0} in the Brand Allocation(JLRC) section.';

            var returnValue = checkIsNull(currentData, fields, msgTpl);

            if (!returnValue) {
                return returnValue;
            }
        }
    }
    //Brand Allocation（CJLR）提交非空验证
    if (store5.data.items.length > 0) {
        var fields = ['DescriptionOfSuppliesServices', 'ProjectActivity', 'JASharingRatio', 'JACost', 'CostCenter', 'JAWBS', 'LRSharingRatio', 'LRCost', 'LRWBS'];

        for (var i = 0; i < store5.data.items.length; i++) {

            var currentData = store5.data.items[i].data,
                msgTpl = 'Please fill in {0} in the Brand Allocation(CJLR) section.';

            var returnValue = checkIsNull(currentData, fields, msgTpl);

            if (!returnValue) {
                return returnValue;
            }
        }
    }
    //Project X Allocation 非空验证
    if (store6.data.items.length > 0) {
        var fields = ['Department', 'Amount', 'CostCenterForJA', 'JAPer', 'JAAmount', 'CostCenterForLR', 'LRPer', 'LRAmount'];

        for (var i = 0; i < store6.data.items.length; i++) {
            var currentData = store5.data.items[i].data,
                msgTpl = 'Please fill in {0} in the Project X Allocation section.';

            var returnValue = checkIsNull(currentData, fields, msgTpl);

            if (!returnValue) {
                return returnValue;
            }
        }
    }

    //发起时，把多选框中已勾选的值拼接赋值给SpecialApprovers1
    var legal = vm.get('NebulogyForm.ApproversSelection.SpecialApprovers.legal');
    var merchandise = vm.get('NebulogyForm.ApproversSelection.SpecialApprovers.merchandise');
    var it = vm.get('NebulogyForm.ApproversSelection.SpecialApprovers.it');
    var comliance = vm.get('NebulogyForm.ApproversSelection.SpecialApprovers.comliance');
    var tax = vm.get('NebulogyForm.ApproversSelection.SpecialApprovers.tax');
    var SpecialApprovers1 = [];

    if (legal == '1') {
        SpecialApprovers1.push("Legal");
    }
    if (merchandise == '1') {
        SpecialApprovers1.push("Merchandise");
    }
    if (it == '1') {
        SpecialApprovers1.push("IT");
    }
    if (comliance == '1') {
        SpecialApprovers1.push("Comliance");
    }
    if (tax == '1') {
        SpecialApprovers1.push("TAX");
    }

    vm.set('NebulogyForm.sectioncols24.HaveSpecialApprovers1', SpecialApprovers1.length > 0 ? 'yes' : 'no');

    vm.set('NebulogyForm.speical.SpecialApprovers1', SpecialApprovers1.join(','));

    //根据CompanyAllocation表格中的Company的值，如果只存在JLRC,则给文本框Company赋值1，如果只存在CJLR,则给文本框赋值2
    //同时，把JLRC的COST的总和赋值给JLRCAmount，把CJLR的COST的总和赋值给CJLRAmount
    var store = ref.datagrid3.getStore();
    var companyJLRC = 0;
    var companyCJLR = 0;
    var JLRCAmount = 0;
    var CJLRAmount = 0;
    var CompanyAmount = 0;

    for (var i = 0; i < store.getCount(); i++) {
        var cost = store.getAt(i).data.Cost;
        var company = store.getAt(i).data.Company;
        CompanyAmount = floatAdd(CompanyAmount, cost);
        if (company == 'JLRC' || company == 'LRE') {
            companyJLRC += 1;
            JLRCAmount = floatAdd(JLRCAmount, cost);
        } else if (company == 'CJLR') {
            companyCJLR += 1;
            CJLRAmount = floatAdd(CJLRAmount, cost);
        }
    }
    if (companyJLRC > 0 && companyCJLR == 0) {
        vm.set('NebulogyForm.companySection.company', '1');
    }
    else if (companyJLRC == 0 && companyCJLR > 0) {
        vm.set('NebulogyForm.companySection.company', '2');
    }
    else {
        vm.set('NebulogyForm.companySection.company', '0');
    }
    //给Amount赋值
    vm.set('NebulogyForm.amount.JLRCAmount', JLRCAmount);
    vm.set('NebulogyForm.amount.CJLRAmount', CJLRAmount);

    var SubTotal = 0;
    //根据PurchaseItems中NetPrice总和，赋值给SubTotal
    var store2 = ref.datagrid2.getStore();
    for (var i = 0; i < store2.getCount(); i++) {
        var TotalPrice = store2.getAt(i).data.TotalPrice;
        SubTotal = floatAdd(SubTotal, TotalPrice);
    }
    vm.set('NebulogyForm.amount.SubTotal', SubTotal);

    var uKCrossCharge = ref.UKCrossCharge.getValue();
    if (uKCrossCharge == "yes") {
        vm.set('NebulogyForm.companySection.company', '1');
        vm.set('NebulogyForm.amount.JLRCAmount', SubTotal);

        var purchaseItemsStore = ref.datagrid2.getStore();
        var companyAllocationStore = ref.datagrid3.getStore();
        var descriptionItems = [];
        var companyAllocationItems = [];
        var editor = ref.datagrid3.getColumns()[0].getEditor();

        Ext.each(purchaseItemsStore.data.items, function (record) {
            descriptionItems.push({
                name: record.get('DescriptionOfSuppliesServices'),
                code: record.get('DescriptionOfSuppliesServices')
            });

            companyAllocationItems.push({
                DescriptionOfSuppliesServices: record.get('DescriptionOfSuppliesServices'),
                ProjectActivity: record.get('ProjectActivity'),
                Company: 'UK'
            });
        });
        editor.getStore().loadData(descriptionItems);
        companyAllocationStore.loadData(companyAllocationItems);

        Ext.each(companyAllocationStore.data.items, function (record) {
            record.set('CompanySharingRatio', 100);
        });

    } else if (uKCrossCharge == 'no') {
        //判断CompanyAllocation中的Cost的总和是否等于PurchaseItems的NetPrice的总和
        if (CompanyAmount != SubTotal) {
            showTipsMsg('Please ensure that the amount is equal')
            return false;
        }

        //判断CompanyAllocation表格中，是否存在balance
        //前提：ExpenseType的值为FME或SE, 对JLRC的balance做卡控
        if (ref.ExpenseType.getValue() == '1' || ref.ExpenseType.getValue() == '2') {
            var store3 = ref.datagrid3.getStore();
            var company;
            for (var i = 0; i < store3.getCount(); i++) {
                company = store3.getAt(i).data.Company;
                if (store3.getAt(i).data.budgetControl == "Y") {
                    if (store3.getAt(i).data.Balance < 0) {
                        showTipsMsg('Balance is negative')
                        return false;
                    }
                }
            }
        }
    }
}


//加法运算    
function floatAdd(arg1, arg2) {
    var r1, r2, m;
    try { r1 = arg1.toString().split(".")[1].length; } catch (e) { r1 = 0; }
    try { r2 = arg2.toString().split(".")[1].length; } catch (e) { r2 = 0; }
    m = Math.pow(10, Math.max(r1, r2));
    return (arg1 * m + arg2 * m) / m;
}    